/*
 * This file is part of quickReminder, a software for gamers
 *
 * Copyright (C) 2006-2008 Lucas Romero
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>.
 */
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using ManagedWinapi.Windows;
using ManagedWinapi.Accessibility;
using GA_ScreenScraper;
using System.Diagnostics;

namespace quickRemindergdf
{
    static class ESLHelpers
    {
        const string prefilter = "<form action=\".*/open_matches/savesms/\" method=\"post\">.*?</form>";
        const string RecentMatchesRegex = "\\s\\w*, (\\d\\d/\\d\\d/\\d\\d \\d\\d:\\d\\d)<.*?<a href=\".*?((player)|(team))/\\d+/\">(.*?)</a>.*?<a.*?href=\".*?/matchsetup/\\d+/\">.*?</a>";
        const string SrvTimeRegex = @">(\d\d/\d\d/\d\d \d\d:\d\d)h\s\|.*/change_timezone/";
        public static string getMatchLink()
        {
            try
            {
                ManagedWinapi.Windows.SystemWindow aeqwin = new SystemWindow(Win32.FindWindowEx(IntPtr.Zero, IntPtr.Zero, "ESL Aequitas - Steam Version *BETA*", "ThunderRT6FormDC"));
                foreach (SystemWindow w in aeqwin.AllChildWindows/*.AllDescendantWindows*/)
                {
                    if (w.Title == "ESL Aequitas - Steam Version *BETA*")
                    {
                        foreach (SystemWindow w2 in w.AllChildWindows)
                        {
                            if (w2.ClassName == "ThunderRT6TextBox")
                            {
                                SystemAccessibleObject stopmon = SystemAccessibleObject.FromWindow(w2, AccessibleObjectID.OBJID_WINDOW);
                                foreach (SystemAccessibleObject o in stopmon.Children)
                                    if (o.RoleIndex == 42)
                                    {
                                        return o.Value;
                                    }
                                break;
                            }
                        }
                        break;
                    }
                }
            }
            catch { }
            return string.Empty;
        }
        public static string GetHTML(string URL, string cook)
        {
            return GetHTML(URL, new Cookie("COOKIE", cook, "/", ".esl.eu"));
        }
        public static string GetHTML(string URL, Cookie cook)
        {
            string HTML = String.Empty;
            HttpWebRequest request;
            HttpWebResponse response;
            StreamReader answer = null;
            request = (HttpWebRequest)WebRequest.Create(URL);
            request.Timeout = 30000;
            request.CookieContainer = new CookieContainer();
            request.CookieContainer.Add(cook);
            //get response
            
            try
            {
                response = (HttpWebResponse)request.GetResponse();
                answer = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
                //while (m_UploadStatus != ItemUploadStatus.Aborted && answer.ReadLine() != String.Empty)
                //{
                //HTML += answer.ReadLine();
                //}
                HTML = answer.ReadToEnd();
                /*StreamWriter s = new StreamWriter("bla.txt");
                s.Write(HTML);
                s.Close();*/
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                answer.Close();
            }
            return HTML;
        }
        public static bool isMatchInReach(TimeSpan before,TimeSpan after, string cookie, bool debug)
        {
            bool opengame = false;
            //debug filename
            //string filename = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "debug" + DateTime.Now.ToString().Replace(":", "-") + ".txt";
            //create cookie for login
            Cookie cook = new Cookie("COOKIE", cookie, "/", ".esl.eu");
            //get html source
            string html = GetHTML("http://www.esl.eu/change_lang/en/?ref=/open_matches/", cook);

            //extract timestring from source
            string servertime = Regex.Match(html, SrvTimeRegex, RegexOptions.Singleline | RegexOptions.IgnoreCase).Groups[1].Value;
            //convert time from english MM/DD/YYYY to DD/MM/YYYY
            string servertime2 = servertime.Substring(3, 2) + "/" + servertime.Substring(0, 2) + servertime.Substring(5, servertime.Length - 5) + ":00";
            DateTime ServerTime = Convert.ToDateTime(servertime2);
            Trace.WriteLine("Time on ESL-Server: " + ServerTime.ToString());


            //strip garbage from html
            if (Regex.Match(html, prefilter, RegexOptions.Singleline | RegexOptions.IgnoreCase).Success)
                html = Regex.Match(html, prefilter, RegexOptions.Singleline | RegexOptions.IgnoreCase).Value;
            
            MatchCollection matches = Regex.Matches(html, RecentMatchesRegex, RegexOptions.Singleline | RegexOptions.IgnoreCase);
            foreach (Match m in matches)
            {
                //extract timestring from matchinfo
                string s = m.Groups[1].Value;
                //convert time from english MM/DD/YYYY to DD/MM/YYYY
                string s2 = s.Substring(3, 2) + "/" + s.Substring(0, 2) + s.Substring(5, s.Length - 5);
                Trace.WriteLine("MATCH vs. " + m.Groups[5].Value + "@" + s + "(" + s2 + ")");
                DateTime matchdate = Convert.ToDateTime(s2);
                Trace.WriteLine("I think it's @" + matchdate.ToString());
                TimeSpan t = ServerTime - matchdate;
                Trace.WriteLine("Game is in " + t.Negate().ToString());
                if (IsDateBetween( matchdate, ServerTime, before, after))
                {
                    opengame = true;
                    break;
                }
            }
            Trace.WriteLine("HTML DUMP:");
            Trace.Write(html);
            return opengame;
        }
        private static bool IsDateBetween(DateTime a, DateTime start, DateTime end)
        {
            return (a >= start && a <= end);
        }
        private static bool IsDateBetween(DateTime target, DateTime a, TimeSpan before, TimeSpan after)
        {
            return (a >= target-before && a <= target+after);
        }
    }
}
